package com.coinread.hr.tools.service.impl;

import com.coinread.hr.tools.bean.Info;
import com.coinread.hr.tools.bean.User;
import com.coinread.hr.tools.bean.persistence.TablePersistence;
import com.coinread.hr.tools.bean.persistence.UserPersistence;
import com.coinread.hr.tools.service.ExcelService;
import com.coinread.hr.tools.utils.HtmlUtils;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

@Slf4j
@Service
public class ExcelServiceImpl implements ExcelService {

    @Autowired
    private TablePersistence tablePersistence;

    @Autowired
    private UserPersistence userPersistence;

    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String sender;

    @Override
    public void getList(MultipartFile file) {

        try {
            String fileName = file.getOriginalFilename();
            InputStream fs = file.getInputStream();
            boolean is03Excell = fileName.matches("^.+\\.(?i)(xls)$")?true:false;
            if (is03Excell)
                log.info("是03Excel");
            Workbook workbook = is03Excell ? new HSSFWorkbook(fs):new XSSFWorkbook(fs);
            Sheet sheet = workbook.getSheet("工作表1");
            if (sheet == null){
                log.info("Sheet名称为：{}的Sheet不存在!","工作表1");
                sheet = workbook.getSheetAt(0);
            }
            Row zeroRow = sheet.getRow(0);
            for (int i = 0;i<20;i++) {
                Cell cell = zeroRow.getCell(i);
                if (cell!=null&&StringUtils.isNotBlank(cell.getStringCellValue())){
                    tablePersistence.add(i,cell.getStringCellValue());
                }
            }
            for (int i =1;i<=50;i++) {
                Info info = new Info();
                User user = new User();
                user.setId(i);
                Map<Integer,String> map = new HashMap<>();
                Row row = sheet.getRow(i);
                boolean add = false;
                if (row!=null) {
                    for (int j = 0; j <= 20; j++) {
                        Cell cell = row.getCell(j);
                        if (cell!=null)
                            cell.setCellType(CellType.STRING);
                        if (cell != null && StringUtils.isNotBlank(cell.getStringCellValue())&&cell.getStringCellValue().trim()!="") {
                            if (j == tablePersistence.getName()) {
                                user.setName(cell.getStringCellValue());
                            }
                            if (j == tablePersistence.getEmail()) {
                                user.setEmail(cell.getStringCellValue());
                            }
                            map.put(j, cell.getStringCellValue());
                        }
                        add = true;
                        info.setUser(user);
                        info.setInfo(map);
                    }
                }
                if (add)
                    userPersistence.add(info);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public int send(int id){
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message);
        try {
            Info info = userPersistence.getInfo().get(id);
            Calendar calendar = Calendar.getInstance();
            String title = "工资明细-"+info.getUser().getName()+"-"+calendar.get(Calendar.YEAR)+"年"+calendar.get(Calendar.MONTH)+"月";
            helper.setFrom(sender);
            helper.setTo(info.getUser().getEmail());
            helper.setText(HtmlUtils.genHtmlMailContent(null,"",null),true);
            helper.setSubject("工资明细-宋亚旭-2018年5月");
            javaMailSender.send(message);
            return 1;
        }catch (Exception e){
            log.error("发送失败 e = {}",e.getMessage());
            log.info("相关信息如下：{}",HtmlUtils.genHtmlMailContent(null,"",null));
            return 0;
        }
    }

    @Override
    public void setNull() {
        tablePersistence.setTableNameList(new HashMap<>());
        userPersistence.setInfo(Lists.newArrayList());
    }
}
